<?php

class Cache_File {
    
    public $path;
    
    public $life = 3600;
    
    public $key;
    
    public function __construct () {
        $this->path = ROOT_PATH . 'Cache';
    }
    
    public function isExpired () {
        return !($this->_getExpireTime($this->path . $this->key) > time());
    }
    
    public function set ($value) {
        $value = "<!--" . (time() + $this->life) . "-->\n" . $value;
        
        $fp = fopen($this->path . $this->key, 'w');
        fwrite($fp, $value);
        fclose($fp);
    }
    
    public function get () {
        return $this->_getContent();
    }
    
    private function _getContent () {
        $key = $this->path . $this->key;
        if (! is_file($key) || ! is_readable($key)) {
            return false;
        } else {
            $fp = fopen($key, 'r');
            fgets($fp, 1024);
            while (! feof($fp)) {
                $content .= fgets($fp, 4096);
            }
            fclose($fp);
            return $content;
        }
    }
    
    private function _getExpireTime () {
    	echo 123;
        $file = $this->path . $this->key;
        if (! is_file($file) || ! is_readable($file)) {
            return 0;
        } else {
            $fp = fopen($file, 'r');
            $first_line = fgets($fp, 1024);
            fclose($fp);
            preg_match('~<!--([0-9]+)-->~', $first_line, $match);
            return $match[1];
        }
    }
}
?>